﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

namespace iTFF.WPF.Helpers
{
    public static class WebHelper
    {

        /// <summary>
        /// Submits a GET resquest
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public static string SubmitRequestAndGetResponse(string uri)
        {
            return SubmitRequestAndGetResponse(uri, null, false);
        }

        /// <summary>
        /// Submits a GET request with specified args
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static string SubmitRequestAndGetResponse(string uri, string args)
        {
            return SubmitRequestAndGetResponse(uri, args, false);
        }

        /// <summary>
        /// Submit a GET or POST request and returns the response as string
        /// </summary>
        /// <param name="uri">Standard URL</param>
        /// <param name="args">Arguments without the "?". Can be null</param>
        /// <param name="post">POST or not</param>
        /// <returns></returns>
        public static string SubmitRequestAndGetResponse(string uri, string args, bool post)
        {
            string userAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"; // WINDOWS
            //string userAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.9) Gecko/20071110 Firefox/2.0.0.9"; // LINUX
            //string userAgent = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"; // GOOGLE BOT
            string referer = "http://www.google.com/";

            if (!post)
            {
                // standard get 
                WebClient wc = new WebClient();
                wc.Headers[HttpRequestHeader.UserAgent] = userAgent;
                wc.Headers[HttpRequestHeader.Cookie] = "pass=deleted";
                wc.Encoding = Encoding.UTF8;


                try
                {
                    if (args == null)
                        return wc.DownloadString(uri);
                    else
                        return wc.DownloadString(uri + "?" + args);
                }
                catch (WebException)
                {
                    return null;
                }
            }
            else
            {
                // post 
                try
                {
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
                    req.Method = WebRequestMethods.Http.Post;
                    req.ContentType = "application/x-www-form-urlencoded";
                    // simuler firefox
                    req.Referer = referer;
                    req.UserAgent = userAgent;

                    byte[] bytes = Encoding.Default.GetBytes(args);
                    req.ContentLength = bytes.Length;

                    Stream reqStream = req.GetRequestStream();
                    reqStream.Write(bytes, 0, bytes.Length);
                    reqStream.Close();

                    WebResponse resp = req.GetResponse();

                    Stream newStream = resp.GetResponseStream();
                    StreamReader sr = new StreamReader(newStream);
                    string result = sr.ReadToEnd();
                    sr.Dispose();
                    newStream.Dispose();
                    return result;
                }
                catch (WebException)
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// Submits a google "I'm feeling lucky" request, in order to directly go to the result page (usefull to avoid search results page)
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public static string GoogleFeelingLuckyRequest(string uri)
        {
            string res = SubmitRequestAndGetResponse(uri, null, false);

            if (Regex.IsMatch(res, "Your search .* did not match any documents."))
                return null;
            else
                return res;
        }

    }
}
